<?php
namespace Home\Model;

/**
 * 实现postgresql数据操作模型类
 * 注意：为区别于自定义model，数据库连接类方法命名采用公共函数的命名规范
 * @author yukari
 * 2018-06-26
 */
class PostgresqlModel{

	//数据库连接
	protected  $db_con = null;

	/**
	 * 构造函数，负责数据库的连接
	 * @author yukari
	 * 2018-06-26
	 */
	public function __construct(){
		$host = "host=".C("PG_HOST");
        $port = "port=".C("PG_PORT");
        $dbname = "dbname=".C("PG_NAME");
        $credentials = "user=".C("PG_USER")." "."password=".C("PG_PWD");

        $pg_db = pg_connect( "$host $port $dbname $credentials" );
        if($pg_db){

            $this->db_con = $pg_db;
        } else {

            echo "postgresql连接失败";
        }
	} 

	/**
     * postgresql执行insert
     * @param $sql 要执行的语句;$re_colum 返回的字段，默认id
     * @return 执行sql后$re_colum字段的值
     * @author yukari
     * 2018-08-17
     */
	public function mpg_insert($sql,$re_colum="id"){

        $sql = $sql." RETURNING $re_colum;";

        $sql_res = pg_query($this->db_con, $sql);

        if($sql_res){
            $row = pg_fetch_all($sql_res);

            return $row[0][$re_colum];
        }else{

            return false;
        }
    }

    /**
     * postgresql执行select
     * @param $sql 要执行的语句;$re_colum 返回的字段，默认id
     * @return 执行sql后$re_colum字段的值
     * @author yukari
     * 2018-08-17
     */ 
    public function mpg_select($sql){
        $sql_res = pg_query($this->db_con, $sql);

        if($sql_res){

            $row = pg_fetch_all($sql_res);
            return $row;
        }else{

            return false;
        }
    }

    /**
     * postgresql执行update
     * @param $sql 要执行的语句
     * @return 执行sql后受影响的行数
     * @author zhou.long
     * 2018-08-17
     */
    public function mpg_update($sql){
        $sql_res = pg_query($this->db_con, $sql);

        if($sql_res){

            $row = pg_affected_rows($sql_res);
            return $row;
        }else{

            return false;
        }
    }

    /**
     * postgresql执行delete
     * @param $sql 要执行的语句
     * @return 执行sql后受影响的行数
     * @author zhou.long
     * 2018-08-17
     */
    public function mpg_delete($sql){
        $sql_res = pg_query($this->db_con, $sql);

        if($sql_res){

            $row = pg_affected_rows($sql_res);
            return $row;
        }else{

            return false;
        }        
    }



}